from django.contrib.auth.decorators import login_required
from django.http.response import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, redirect, get_object_or_404
from django.template import RequestContext
from page.models import Page
from question.models import Question
from page.tree_utils import insert_page
from django.contrib.auth.models import User
from test.models import DiagnosticTest
from page.tree_utils import remove_page_from_tree

def trash_pages(request):
    """
    List trashed pages.
    """
    pages = Page.objects.filter(trash=True)
    return render(request, 'pages.html', {'pages':pages})

def trash_users(request):
    """
    List trashed users.
    """
    users = User.objects.filter(is_active=False)
    return render(request, 'users.html', {'users':users})

def trash_questions(request):
    """
    List trashed questions.
    """
    questions = Question.objects.filter(trash=True)
    return render(request, 'questions.html', {'questions': questions})

def restore_page(request, page_id):
    """
    Restores page from trash.
    """
    page = get_object_or_404(Page, id=page_id)
    #If the page is an diagnostic test, do not insert it into the tree
    try:
        DiagnosticTest.objects.get(pk=page_id)
    except:
        insert_page(None ,page)
        
    page.trash = False
    page.save()
    
    return redirect('trash.views.trash_pages')

def restore_user(request, username):
    """
    Restores user from trash.
    """
    user = get_object_or_404(User, username=username)
    user.is_active= True
    user.save()
    return redirect('trash.views.trash_users')

def restore_question(request, question_id):
    """
    Restores question from trash.
    """
    question = get_object_or_404(Question, pk=question_id)
    question.trash = False
    question.save()
    return redirect('trash.views.trash_questions')


def delete_page(request,  page_id):
    """
    Delete page permanently.
    """ 
    try:
        page = Page.objects.get(id=page_id)
        remove_page_from_tree(page)
        page.delete()
        
        return redirect('trash.views.trash_page')
    
    except Page.DoesNotExist:
        return redirect('trash.views.trash_page')
